package com.open.capacity.reimburse.service.impl;

import com.open.capacity.model.system.LoginAppUser;
import com.open.capacity.model.system.SysUser;
import com.open.capacity.reimburse.util.uuid.UUIDUtils;
import com.open.capacity.reimburse.dao.SysEmailRecipientDao;
import com.open.capacity.reimburse.entity.SysEmailRecipient;
import com.open.capacity.utils.SysUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.open.capacity.commons.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.open.capacity.commons.CodeEnum;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.collections4.MapUtils;

import com.open.capacity.reimburse.entity.SysEmail;
import com.open.capacity.reimburse.dao.SysEmailDao;
import com.open.capacity.reimburse.service.SysEmailService;
import org.springframework.transaction.annotation.Transactional;


@Service
public class SysEmailServiceImpl implements SysEmailService {

    @Autowired
    private SysEmailDao emailDao;

    @Autowired
    private SysEmailRecipientDao emailRecipientDao;

    /**
     * 添加
     *
     * @param email
     */
    @Transactional(rollbackFor = Exception.class)
    public int save(SysEmail email) {
        LoginAppUser loginUser = SysUserUtil.getLoginAppUser();

        Date now = new Date();
        email.setId(UUIDUtils.getOriginalUUIDWithoutBar());
        email.setSenderTime(now);
        email.setSenderUserid(loginUser.getId());
        email.setSenderUsername(loginUser.getRealName());
        email.setUpdateUserid(loginUser.getId());
        email.setUpdateUsername(loginUser.getRealName());
        email.setUpdateTime(now);

        for (SysEmailRecipient item : email.getRecipientList()) {
            item.setId(UUIDUtils.getOriginalUUIDWithoutBar());
            item.setEmailId(email.getId());
            item.setTheme(email.getTheme());
            item.setFiles(email.getFiles());
            item.setContent(email.getContent());
            item.setStatus(1);
            item.setSenderUserid(email.getSenderUserid());
            item.setSenderUsername(email.getSenderUsername());
            item.setSenderTime(email.getSenderTime());
            item.setUpdateTime(now);
            item.setUpdateUserid(loginUser.getId());
            item.setUpdateUsername(loginUser.getRealName());
            emailRecipientDao.save(item);
        }

        return emailDao.save(email);
    }

    /**
     * 修改
     *
     * @param email
     */
    public int update(SysEmail email) {
        email.setUpdateTime(new Date());
        return emailDao.update(email);
    }


    /**
     * 删除
     *
     * @param id
     */
    public int delete(String id, String type) {
        SysUser loginUser = SysUserUtil.getLoginAppUser();
        switch (type) {
            case "1":
                emailRecipientDao.updateStatus(id, loginUser.getId(), -1);
                break;
            case "2":
            case "3":
            case "4":
                emailDao.updateStatus(id, 0);
                break;
        }
        return 1;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int thoroughRemove(String id, String type) {
        SysUser loginUser = SysUserUtil.getLoginAppUser();
        emailRecipientDao.deleteByUserid(id, loginUser.getId());
        emailDao.updateStatus(id, -1);
        return 1;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteDraft(String id, String type) {
        return emailDao.updateStatus(id, -1);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int restore(String id, String type) {
        SysUser loginUser = SysUserUtil.getLoginAppUser();
        emailDao.updateStatus(id, 1);
        return emailRecipientDao.updateStatus(id, loginUser.getId(), 1);
    }

    /**
     * 查询记录
     *
     * @param id
     * @return
     */
    public SysEmail findById(String id) {
        SysUser loginUser = SysUserUtil.getLoginAppUser();

        SysEmail email = emailDao.findById(id);
        List<SysEmailRecipient> recipientList = emailRecipientDao.findByEmailId(email.getId());
        email.setAddress(recipientList.stream().filter(t -> t.getRecipientStatus().equals(0)).map(SysEmailRecipient::getRecipientId).collect(Collectors.joining(",")));
        email.setCopysend(recipientList.stream().filter(t -> t.getRecipientStatus().equals(1)).map(SysEmailRecipient::getRecipientId).collect(Collectors.joining(",")));
        email.setBccsend(recipientList.stream().filter(t -> t.getRecipientStatus().equals(2)).map(SysEmailRecipient::getRecipientId).collect(Collectors.joining(",")));

        //已读
        if(!email.getUpdateUserid().equals(loginUser.getId())){
            emailRecipientDao.updateIsRead(email.getId(),loginUser.getId());
        }

        return email;
    }

    /**
     * 分页
     *
     * @param params
     * @return
     */
    public PageResult<SysEmail> pageAll(Map<String, Object> params) {
        SysUser loginUser = SysUserUtil.getLoginAppUser();

        //设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
        if (MapUtils.getInteger(params, "page") != null && MapUtils.getInteger(params, "limit") != null)
            PageHelper.startPage(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"), true);

        String type = params.get("type").toString();
        List<SysEmail> list = new ArrayList<>();
        switch (type) {
            case "1"://收件箱
                params.put("recipientId", loginUser.getId());
                params.put("status", 1);
                list = emailRecipientDao.findAll(params);
                break;
            case "2"://草稿箱
                params.put("updateUserid", loginUser.getId());
                params.put("sendStatus", 0);
                params.put("status", 0);
                list = emailDao.findAll(params);
                list.forEach(item -> {
                    List<SysEmailRecipient> recipientList = emailRecipientDao.findByEmailId(item.getId());
                    item.setAddress(recipientList.stream().filter(t -> t.getRecipientStatus().equals(0)).map(SysEmailRecipient::getRecipientId).collect(Collectors.joining(",")));
                    item.setCopysend(recipientList.stream().filter(t -> t.getRecipientStatus().equals(1)).map(SysEmailRecipient::getRecipientId).collect(Collectors.joining(",")));
                    item.setBccsend(recipientList.stream().filter(t -> t.getRecipientStatus().equals(2)).map(SysEmailRecipient::getRecipientId).collect(Collectors.joining(",")));
                });
                break;
            case "3"://发件箱
                params.put("updateUserid", loginUser.getId());
                params.put("sendStatus", 1);
                params.put("status", 1);
                list = emailDao.findAll(params);
                list.forEach(item -> {
                    List<SysEmailRecipient> recipientList = emailRecipientDao.findByEmailId(item.getId());
                    item.setAddress(recipientList.stream().filter(t -> t.getRecipientStatus().equals(0)).map(SysEmailRecipient::getRecipientId).collect(Collectors.joining(",")));
                    item.setCopysend(recipientList.stream().filter(t -> t.getRecipientStatus().equals(1)).map(SysEmailRecipient::getRecipientId).collect(Collectors.joining(",")));
                    item.setBccsend(recipientList.stream().filter(t -> t.getRecipientStatus().equals(2)).map(SysEmailRecipient::getRecipientId).collect(Collectors.joining(",")));
                });
                break;
            case "4"://回收站
                //已删除收件
                params.put("recipientId", loginUser.getId());
                params.put("status", -1);
                list = emailRecipientDao.findAll(params);

                //已删除发件
                params.put("updateUserid", loginUser.getId());
                params.put("status", 0);
                List<SysEmail> list2 = emailDao.findAll(params);
                list.addAll(list2);
                break;

        }

        PageInfo<SysEmail> pageInfo = new PageInfo(list);
        return PageResult.<SysEmail>builder().data(pageInfo.getList()).resp_code(CodeEnum.SUCCESS.getCode()).count(pageInfo.getTotal()).build();
    }

    /**
     * 列表
     *
     * @param params
     * @return
     */
    public List<SysEmail> findAll(Map<String, Object> params) {
        return emailDao.findAll(params);
    }

}
